package com.httpdemo.http_teaching_server.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/cache")
public class CacheController {

    /* 1️⃣ 强缓存：max-age=30s */
    @GetMapping("/strong")
    public ResponseEntity<Map<String, String>> strong() {
        return ResponseEntity.ok()
                .header(HttpHeaders.CACHE_CONTROL, "max-age=30")
                .body(Map.of("ts", LocalDateTime.now().toString(),
                        "type", "强缓存 max-age=30"));
    }

    /* 2️⃣ 对比缓存：ETag + Last-Modified */
    @GetMapping("/etag/{id}")
    public ResponseEntity<Map<String, Object>> etag(@PathVariable Long id,
                                                    @RequestHeader(value = "If-None-Match", required = false) String ifNoneMatch,
                                                    @RequestHeader(value = "If-Modified-Since", required = false) String ifModifiedSince) {
        String currentEtag = "\"v" + id + "\"";
        if (currentEtag.equals(ifNoneMatch)) {
            return ResponseEntity.status(HttpStatus.NOT_MODIFIED).build();
        }
        return ResponseEntity.ok()
                .eTag(currentEtag)
                .lastModified(LocalDateTime.now().minusMinutes(5)
                        .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli())
                .body(Map.of("id", id,
                        "data", "some-data-" + id,
                        "type", "对比缓存 ETag"));
    }
}